#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>


#if 0
float get_temperature();

int main(int argc,char **argv)
{
	float		t;
	float		rv = -1;
	rv = get_temperature();

	if(rv<0)
	{
		printf("get temperature failure! return value:%s\n");
		return -1;
	}
	printf("return value:%.3f\n",rv);

	return 0;

}
#endif

int get_temperature(float *temp)
{
	int			fd = -1;
	int			rv = -1;
	DIR			*opdir = NULL;
	struct	dirent		*rddir = NULL;	
	char			*ptr;
	char			dir_path[64] = "/sys/bus/w1/devices/";
	char 			buf[1024];
	char 			ds18b20_path[64];

	opdir = opendir(dir_path);

	if(!opdir)
	{
		printf("open the dir failure:%s\n",strerror(errno));
		return -1;
	}

	while(NULL !=(rddir = readdir(opdir)))
	{
		if(strstr(rddir->d_name,"28-"))
		{
			strncpy(ds18b20_path,rddir->d_name,sizeof(ds18b20_path));
		}
	}
	
	strncat(dir_path,ds18b20_path,sizeof(dir_path)-strlen(ds18b20_path));
	strncat(dir_path,"/w1_slave",sizeof(dir_path)-strlen("/w1_slave"));
	//printf("dir_path:%s\n",dir_path);


	fd = open(dir_path,O_RDONLY);

	if(fd<0)
	{
		printf("open the file failure:%s\n",strerror(errno));
		return -2;
	}

	memset(buf,0,sizeof(buf));

	rv = read(fd,buf,sizeof(buf));

	if(rv<0)
	{
		printf("read the file failure:%s\n",strerror(errno));
		return -3;
	}

	//printf("buf:%s\n",buf);

	ptr = strstr(buf,"t=");

	if(!ptr)
	{
		printf("can not find t=string!\n");
		return -4;
	}

	ptr = ptr+2;
	*temp = atof(ptr)/1000;
	//printf("ds18b20 temperarure:%.3f\n",*temp);

	close(fd);

	//return temp;


}
